<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="myElement"></div>
    <script>
        // 1、创建并触发自定义事件
        const eventName = 'myCustomEvent';
        const eventDetail = { key1: 'value1', key2: 42 };
        const myEvent = new CustomEvent(eventName, { detail: eventDetail, bubbles: true, cancelable: true });
        const element = document.getElementById('myElement'); // 确保页面上有一个ID为'myElement'的元素
        

        // 2、全局监听自定义事件
        document.addEventListener(eventName, (event) => {
            const eventData = event.detail;
            console.log('Custom event triggered globally:', eventData.key1, eventData.key2);
        });
        

        // 3、在这里进行触发事件
        element.dispatchEvent(myEvent);
    </script>
</body>

</html>